package ar.edu.utn.frsf.tpae.a2012.g02.dao.implementacion;

import java.lang.reflect.ParameterizedType;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;

import ar.edu.utn.frsf.tpae.a2012.g02.dao.GenericDAO;
import ar.edu.utn.frsf.tpae.a2012.g02.models.Cliente;

public class GenericHibernateDAO<E> implements GenericDAO<E> {

	// Setter utilizado por Spring.
	@Autowired(required = true)
	private SessionFactory sessionFactory;

	/*
	 * // Setter utilizado por Spring.
	 * 
	 * @Autowired(required = true) public void setSessionFactory(SessionFactory
	 * factory) { this.sessionFactory = factory; }
	 */

	private Session getCurrentSession() {
		return sessionFactory.getCurrentSession();
	}

	@Override
	public E saveOrUpdate(E entity) {
		getCurrentSession().saveOrUpdate(entity);
		return entity;
	}

	@Override
	public boolean delete(E entity) {
		getCurrentSession().delete(entity);
		return true;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<E> getAll() {
		Query query = getCurrentSession().createQuery("from " + Cliente.class.getName());
		return query.list();
	}

	@SuppressWarnings("unchecked")
	@Override
	public E getById(int id) {
		return (E) getCurrentSession().get(getEntityClass(), id);
	}

	@SuppressWarnings("unchecked")
	private Class<E> getEntityClass() {
		ParameterizedType ptype = (ParameterizedType) getClass().getGenericSuperclass();
		return (Class<E>) ptype.getActualTypeArguments()[0];
	}
}
